package com.mebs.edi.scheduler;

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

import com.mebs.edi.datalayer.DaoFactory;

public class InitApplication implements ServletContextListener {
	
	private static final Logger LOG = Logger.getLogger(InitApplication.class);
	
	private static Properties applicationProperties = new Properties();
	
	public static final String APPLICATION_PROPERTIES = "application.properties";
	
	public static final String PROPERTY_RMI_REGISTRY_PORT = "rmi.registry.port";

	public void contextDestroyed(ServletContextEvent arg0) {
		LOG.debug(Thread.currentThread().getName() + ": stopping the application");
	}

	public void contextInitialized(ServletContextEvent arg0) {
		LOG.debug("starting application init");
		
		try {
			LOG.debug("getting application properties");
	        InputStream is = getClass().getResourceAsStream("/" + APPLICATION_PROPERTIES);
	        if (is != null) {
	        	applicationProperties.load(is);
	            is.close();
	            is = null;
	        } else {
	        	LOG.error(APPLICATION_PROPERTIES + " could not be located in classpath.");
	        }
			
			LOG.debug("initializing JPA mappings");
			DaoFactory.getInstance().getGenericDao();
			
			LOG.debug("starting job scheduler (see jobs.xml in classpath for the list of jobs)");
	        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
	        scheduler.start();
        
        } catch (Exception e) {
        	LOG.fatal("Application init failed", e);
        }
	}

	public static Properties getApplicationProperties() {
		return applicationProperties;
	}
}
